package org.jetlinks.demo.protocol.siterwell.tcp.message;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.demo.protocol.siterwell.tcp.TcpPayload;
import org.jetlinks.demo.protocol.siterwell.tcp.util.ByteUtils;
import org.jetlinks.demo.protocol.siterwell.tcp.util.Validator;

@Slf4j
@AllArgsConstructor
@Getter
public class S2DReadSensor implements TcpPayload {



    private String gatewayId;
    private String messageId;
    private String serialNo;

    public S2DReadSensor(FunctionInvokeMessage invokeMessage) {
        this.messageId = invokeMessage.getMessageId();
        this.gatewayId = invokeMessage.getDeviceId();
        this.serialNo = ByteUtils.byteToHex(Validator.calculateCheckValue(ByteUtils.hexStringToBytes(messageId)));
    }

    @Override
    public byte[] toBytes() {
        StringBuilder sb = new StringBuilder();
        sb.append("57");    // 固定头  1字节
        sb.append(serialNo);      // 流水号  1字节
        sb.append("20");    // 版本号  1字节
        sb.append(gatewayId);   // 网关ID 3字节
        sb.append("00000000");  // 网关信号，子设备信号，子设备类型，子设备最高ID ，各1字节，共四个字节
        sb.append("0a");        // 网关类型 ， 固定为0A
        sb.append("20");       // 命令
        sb.append("00");        // 数据长度 ， 无数据，故为零
        byte checkValue = Validator.calculateCheckValue(ByteUtils.hexStringToBytes(sb.toString()));
        sb.append(ByteUtils.byteToHex(checkValue));                     // 校验值
        if (log.isDebugEnabled()) {
            log.debug(String.format("read sensor hex str : %s", sb));
        }

        return ByteUtils.hexStringToBytes(sb.toString());
    }

    @Override
    public void fromBytes(byte[] bytes, int offset) {

    }
}
